<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 6/30/17
 * Time: 3:21 PM
 */
declare(strict_types=1);

namespace application\module\admin\addon\sign\model;

use application\module\admin\addon\model\AddonModel;
use application\module\admin\addon\Sign;
use PharIo\Manifest\InvalidEmailException;
use wshore\core\Dao;
use wshore\helper\Validator;
use wshore\throws\db\RecordNotFoundException;

/**
 * Class UserModel 用户模型
 * @property string $username   账号
 * @property string $password   密码,默认为123456的md5+sha1加密后的值
 * @property string $email      电子邮件
 * @property string $nickname   昵称
 * @property string $avatar     头像
 * @property string $disable    禁用情况,0-禁用 非0-启用
 * @property string $update_time    资料修改时间
 * @property string $register_time  注册时间
 * @property string $meta       附加信息
 * @property string $home_page home页面
 *
 * @package application\module\admin\addon\sign\model
 */
class UserModel extends AddonModel
{

    protected function struct(): string
    {
        return "  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',
  `username` varchar(255) NOT NULL COMMENT '账号名称',
  `password` char(32) NOT NULL DEFAULT 'd93a5def7511da3d0f2d171d9c344e91' COMMENT '默认为123456的md5+sha1加密后的值',
  `email` varchar(64) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT '电子邮件',
  `nickname` varchar(255) NOT NULL DEFAULT '' COMMENT '昵称',
  `avatar` varchar(60000) CHARACTER SET ascii NOT NULL DEFAULT '/static/img/da.jpg' COMMENT '头像，可以是图片的base64码，或者图片的URI地址 ',
  `disable` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT '登录允许:0-禁用 非0-启用',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '资料更新时间',
  `register_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '注册时间',
  `home_page` varchar(255) NOT NULL DEFAULT '' COMMENT '登录时的home页面',
  `meta` varchar(255) NOT NULL DEFAULT '' COMMENT '附加信息',
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `username` (`username`)";
    }

    public function install()
    {
        parent::install();
        $tableName = $this->tablePrefix() . $this->tableName();
        $this->exec("INSERT INTO `{$tableName}` (
`id`, `username`, `password`, `email`, `nickname`, `avatar`, `disable`, `update_time`, `register_time`) VALUES
('1', 'root', 'd93a5def7511da3d0f2d171d9c344e91', '784855684@qq.com', 'linzh',
'/assets/img/da.jpg', '0', '2017-05-10 17:32:03', '2017-05-10 17:32:03');
");
    }


    private $__prefix = '';
    private $__table = '';

    protected function tableName()
    {
        return $this->__table;
    }

    protected function tablePrefix()
    {
        return $this->__prefix;
    }


    public function __construct($id = null)
    {
        $instance = Sign::getInstance();

        $this->__table = $instance->tableName;
        $this->__prefix = $instance->tablePrefix;

        parent::__construct();
        $where = [];
        if ($id !== null) {
            if (is_numeric($id)) {
                # 如果是数字，这说明可能是账户ID或者账户的手机号，区别是手机号长度大于10位
                # 而id由于int类型长度的限制最多只有10位的长度
                if (strlen((string)$id) > 10) {
                    # 手机号一般比10位长(@deprecated)
                    $where['phone'] = $id;
                } else {
                    $where['id'] = $id;
                }
            } elseif (strpos($id, '@')) {
                $where['email'] = $id;
            } elseif (strlen($id) >= 26) {
                # dingding unionid 登陆
                $where = ['dingding_unionid' => $id];
            } else {
                $where['username'] = $id;
            }

            $data = $this->where($where)->find();
            if (empty($data)) {
                throw new RecordNotFoundException($id);
            }
            $this->data = $data;
            $this->id = $this->data[$this->pk];
        }
    }


    /**
     * 获取用户列表
     * @param array $ids
     * @return array
     */
    public function getlist(array $ids = []): array
    {
        if ($ids) {
            $_ids = '';
            foreach ($ids as $id) {
                $_ids .= intval($id) . ',';
            }
            $_ids = rtrim($_ids, ',');
            $list = $this->where(" id in ({$_ids})")->select();
        } else {
            $list = $this->select();
        }
        $temp = [];
        foreach ($list as $item) {
            unset($item['password']);
            unset($item['passwd']);
            $temp[$item['id']] = $item;
        }
        return $temp;
    }

    /**
     * 添加账户
     * @param string $username
     * @param string $email
     * @param string $password
     * @param int $disable
     * @return bool
     */
    public function add(string $username, string $email, string $password, int $disable = 0): bool
    {
        $this->username = $username;
        $this->password = $password;
        $this->email = $email;
        $this->disable = (int)$disable;
        return $this->save();
    }


    /**
     * 保存添加或者修改的用户信息
     * @param bool $justInsert
     * @return bool
     * @throws InvalidEmailException
     */
    public function save($justInsert = false): bool
    {
        # 检查电子邮件
        if (!Validator::isEmail($this->email)) throw new InvalidEmailException($this->email);
        # 加密密码
        $this->password = Sign::encryptPassword($this->password);
        # 禁用情况默认为关闭
        $this->disable or $this->disable = 0;
        if (!$this->id) {
            # 如果id为空，这表明这是添加操作，这时候将设定注册时间
            $this->register_time = date('Y-m-d H:i:s');
        }
        return parent::save($justInsert);
    }

    /**
     * 获取用户信息
     * @return array
     */
    public function getInfo(): array
    {
        if (!$this->id) {
            return [];
        }
        return $this->data;
    }


    public static function getManagerMap()
    {
        $list = Dao::getInstance()->query('SELECT DISTINCT id,url FROM l_user;');
        $map = [];
        foreach ($list as $item) {
            $map[$item['id']] = $item['url'];
        }
        return $map;
    }

}